package com.itheima.health.service.impl;


import com.itheima.health.dao.ReportDao;
import com.itheima.health.pojo.ReportData;
import com.itheima.health.service.ReportService;
import com.itheima.health.util.DateUtil;
import com.itheima.health.vo.HotSetmealVO;
import com.itheima.health.vo.MemberVO;
import com.itheima.health.vo.SetMealReportVO;
import com.itheima.health.vo.SetmealCount;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Service
public class ReportServiceImpl implements ReportService {

    @Autowired
    private ReportDao reportDao;

    @Autowired
    ReportService reportService;


    @Override
    public MemberVO getMemberReport() {
        MemberVO memberVO = new MemberVO();

        String[] months = new String[12];
        Integer[] membersReport = new Integer[12];

        LocalDate  nowMonth= LocalDate.now();
        LocalDate  monthLastYear = nowMonth.minusMonths(12);


        for (int i = 0; i <12; i++) {


            LocalDate minusMonths = monthLastYear.plusMonths(i+1);
            months[i]=minusMonths.toString().substring(0,7).replace("-",".");

            LocalDate monthStart = DateUtil.getMonthStart(minusMonths);
            LocalDate monthEnd = DateUtil.getMonthEnd(minusMonths);

            membersReport[i] = reportDao.getMembersReport(monthStart,monthEnd);
        }
        memberVO.setMonths(months);
        memberVO.setMemberCount(membersReport);
        return memberVO;
    }

    @Override
    public SetMealReportVO getSetmealReport() {

        SetMealReportVO setMealReportVO = new SetMealReportVO();


        String[] names = reportDao.getSetmealName();
        setMealReportVO.setSetmealNames(names);

        setMealReportVO.setSetmealCount(reportDao.getSetmealCount());

        return setMealReportVO;
    }

    @Override
    public ReportData getBusinessReportData() {
        //今天
        LocalDate today = LocalDate.now();
        //本周第一天
        LocalDate weekStart = DateUtil.getWeekStart(today);
        //本周最后一天
        LocalDate weekEnd = DateUtil.getWeekEnd(today);
        //本月第一天
        LocalDate monthStart = DateUtil.getMonthStart(today);
        //本月最后一天
        LocalDate monthEnd = DateUtil.getMonthEnd(today);



        //今日新增会员数
        Integer   todayNewMember =   reportDao.getNewMember(today);

        //本周新增会员数
       Integer  thisWeekNewMember = reportDao.getThisWeekNewMember(weekStart,weekEnd);
       //本月新增会员数
        Integer thisMothsNewNumber = reportDao.getThisMothsNewNumber( monthStart,monthEnd);

        //总会员数
        Integer  totalMember =reportDao.getTotalMember();


        //今日预约数
      Integer  todayOrderNumber =  reportDao.getTodayOrderNumber(today);

      //本周预约数
     Integer  thisWeekOrderNumber = reportDao.getThisWeekOrderNumber(weekStart);

     //本月预约数
       Integer  thisMonthOrderNumber = reportDao.getThisMonthOrderNumber(monthStart,monthEnd);



        List<HotSetmealVO> hotSetmealList = new ArrayList<>();
        List<SetmealCount> setmealCount = reportDao.getSetmealCount();

        for (SetmealCount setmeal : setmealCount) {
            DecimalFormat df = new DecimalFormat("0.0000");
            String proportion = df.format(((double) (setmeal.getValue() )/ thisMonthOrderNumber));
            HotSetmealVO hotSetmeal = HotSetmealVO.builder()
                                      .name(setmeal.getName())
                                      .setmeal_count(setmeal.getValue())
                                      .proportion(Double.valueOf(proportion))
                                      .build();
            hotSetmealList.add(hotSetmeal);
        }





        ReportData reportData = ReportData.builder().
                reportDate(LocalDate.now()).
                todayNewMember(todayNewMember).
                thisWeekNewMember(thisWeekNewMember).
                thisMonthNewMember(thisMothsNewNumber).
                totalMember(totalMember)
                .todayOrderNumber(todayOrderNumber)
                .thisWeekOrderNumber(thisWeekOrderNumber)
                .thisMonthOrderNumber(thisMonthOrderNumber)
                .hotSetmeal(hotSetmealList)
                .build();
        return reportData;
    }

    @Override
    public void exportBusinessReport(HttpServletResponse response) {
        LocalDate today = LocalDate.now();
        //查询概览运营数据，提供给Excel模板文件
        ReportData businessData = reportService.getBusinessReportData();
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("template/report_template.xlsx");
        try {
            //基于提供好的模板文件创建一个新的Excel表格对象
            XSSFWorkbook excel = new XSSFWorkbook(inputStream);
            //获得Excel文件中的一个Sheet页
            XSSFSheet sheet = excel.getSheet("Sheet1");

            XSSFRow row1 = sheet.getRow(1);
            sheet.getRow(2).getCell(5).setCellValue(String.valueOf(today));
            //获得第4行
            XSSFRow row = sheet.getRow(4);
            //获取单元格
            row.getCell(5).setCellValue(businessData.getTodayNewMember());
            row.getCell(7).setCellValue(businessData.getTotalMember());

            //获取第五行
            row = sheet.getRow(5);
            row.getCell(5).setCellValue(businessData.getThisWeekNewMember());
            row.getCell(7).setCellValue(businessData.getThisMonthNewMember());

            //获取第七行
            row = sheet.getRow(7);
            row.getCell(5).setCellValue(businessData.getThisWeekNewMember());
            row.getCell(7).setCellValue(businessData.getThisMonthNewMember());

            //获取第八行
            row = sheet.getRow(8);
            row.getCell(5).setCellValue(businessData.getTodayOrderNumber());


            //获取第九行
            row = sheet.getRow(9);
            row.getCell(5).setCellValue(businessData.getThisWeekOrderNumber());



            List<HotSetmealVO> hotSetmeal = businessData.getHotSetmeal();
            for (int i = 0; i < hotSetmeal.size(); i++) {
                    row = sheet.getRow(12 + i);
                    row.getCell(4).setCellValue(hotSetmeal.get(i).getName());
                    row.getCell(5).setCellValue(hotSetmeal.get(i).getSetmeal_count());
                    row.getCell(6).setCellValue(hotSetmeal.get(i).getProportion());

            }


            //通过输出流将文件下载到客户端浏览器中
            ServletOutputStream out = response.getOutputStream();
            response.setContentType("application/vnd.ms-excel");//代表的是Excel文件类型
            response.setHeader("content-Disposition", "attachment;filename=report.xlsx");//指定以附件形式进行下载
            excel.write(out);
            //关闭资源
            out.flush();
            out.close();
            excel.close();

        }catch (IOException e){
            e.printStackTrace();
        }
    }
}
